//
//  SEGForgetPasswordViewController.m
//  ExcellentHome
//
//  Created by 梁昆 on 16/8/27.
//  Copyright © 2016年 陈区. All rights reserved.
//

#import "SEGForgetPasswordViewController.h"

#import <Commom/UITextField+Limit.h>
#import <Commom/SEGSafaKeyboard.h>
#import <Commom/SEGPasswordTextField.h>

#import "SEGForgetPasswordViewModel.h"

@interface SEGForgetPasswordViewController () <UITextFieldDelegate, SGETextFieldLimitDelegate>
 
@property (nonatomic, strong) UIView *bottomView;
@property (nonatomic, strong) UIView *line1View;
@property (nonatomic, strong) UIView *line2View;
@property (nonatomic, strong) UIView *line4View;
@property (nonatomic, strong) UITextField *phoneText;
@property (nonatomic, strong) UITextField *checkText;
@property (nonatomic, strong) SEGPasswordTextField *newpasswordText;
@property (nonatomic, strong) UIButton *getMessButton;
@property (nonatomic, strong) UITextField *checkImgText;
@property (nonatomic, strong) UIImageView *checkImgView;
@property (nonatomic, strong) UIButton *freshCheckImgBtn;
@property (nonatomic, strong) UILabel *getSoundMsgLabel;
@property (nonatomic, strong) UIButton *getSoundMsgButton;
@property (nonatomic, strong) UILabel *passwordRuleLabel;
/// 导航栏右侧确定按钮
@property (nonatomic, strong) UIButton *confirmButton;
 
/// 定时器取消
@property (nonatomic, strong) RACDisposable *disposable;
/// viewModel
@property (nonatomic, strong) SEGForgetPasswordViewModel *viewModel;

@end

@implementation SEGForgetPasswordViewController
 
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self.disposable dispose];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = kColor_bg;
    [self showCustomNavigationBackButton];
    self.title = @"忘记密码";
    self.confirmButton = [self showCustomNavigationRightButtonWithColorTitle:@"确定" titleColor:kColor_T disabledColor:kColor_C];
    self.confirmButton.enabled = NO;
    [self setupUI];

    // 请求密码配置信息
    [self requestPasswordConfig];
    // 刷新图片验证码
    [self freshCheckImgForgetPassword];
    // 绑定信号
    [self seg_bindSignal];
    
    //注册通知 监听用户截屏
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(handleUserDidTakeScreenshot:)
                                                 name:UIApplicationUserDidTakeScreenshotNotification
                                               object:nil];
    if (@available(iOS 11.0, *)) {
        // 监测当前设备是否处于录屏状态
        if ([UIScreen mainScreen].isCaptured) {
            [SEGAlertView showTmepMessageWithMessage:KDetectScreenCapturedTipMessage withtime:2];
        }
        // 监听用户是否录屏
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(handleScreenCapturedDidChange:)
                                                     name:UIScreenCapturedDidChangeNotification
                                                   object:nil];
    }
}

#pragma mark - Bind
- (void)seg_bindSignal {
    RACChannelTo(self.viewModel, checkImgStr) = self.checkImgText.rac_newTextChannel;
    RAC(self.viewModel, phoneStr) = self.phoneText.rac_textSignal;
    RAC(self.viewModel, smsCodeStr) = self.checkText.rac_textSignal;
    RAC(self.viewModel, freshPwdStr) = self.newpasswordText.rac_textSignal;
}

#pragma mark - Load Data
// 请求密码配置
- (void)requestPasswordConfig {
    @weakify(self);
    [self.viewModel.reqConfigSignal subscribeNext:^(id result) {
        @strongify(self);
        self.passwordRuleLabel.text = result;
        NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
        paragraphStyle.lineSpacing = 8 - (self.passwordRuleLabel.font.lineHeight - self.passwordRuleLabel.font.pointSize);
        paragraphStyle.alignment = NSTextAlignmentRight;
        NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
        [attributes setObject:paragraphStyle forKey:NSParagraphStyleAttributeName];
        self.passwordRuleLabel.attributedText = [[NSAttributedString alloc] initWithString:result attributes:attributes];
    }];
}

#pragma mark - UI
- (void)setupUI {
    [self.view addSubview:self.bottomView];
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker* make) {
        make.top.mas_equalTo(0);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.height.mas_equalTo(50 * 4);
    }];

    [self.view addSubview:self.line1View];
    [self.line1View mas_makeConstraints:^(MASConstraintMaker* make) {
        make.top.equalTo(self.bottomView).mas_offset(50);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.height.mas_equalTo(0.5 * kScaleHeight);
    }];
    
    [self.view addSubview:self.line4View];
    [self.line4View mas_makeConstraints:^(MASConstraintMaker* make) {
        make.top.equalTo(self.line1View).mas_offset(50);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.height.mas_equalTo(0.5 * kScaleHeight);
    }];

    [self.view addSubview:self.line2View];
    [self.line2View mas_makeConstraints:^(MASConstraintMaker* make) {
        make.top.equalTo(self.line4View).mas_offset(50);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.height.mas_equalTo(0.5 * kScaleHeight);
    }];

    [self.view addSubview:self.phoneText];
    [self.phoneText mas_makeConstraints:^(MASConstraintMaker* make) {
        make.top.equalTo(self.bottomView).mas_offset(5);
        make.bottom.equalTo(self.line1View.mas_top).mas_offset(-5);
        make.left.equalTo(self.bottomView).mas_offset(20);
        make.right.equalTo(self.bottomView).mas_offset(-10);
    }];
    
    // 图形验证码 输入
    [self.view addSubview:self.checkImgText];
    [self.checkImgText mas_makeConstraints:^(MASConstraintMaker* make) {
        make.top.equalTo(self.line1View).mas_offset(5);
        make.left.equalTo(self.bottomView).mas_offset(20);
        make.right.equalTo(self.bottomView.mas_right).mas_offset(-129 * kScaleWidth);
        make.bottom.equalTo(self.line4View.mas_top).mas_offset(-5);
        make.height.mas_equalTo(44);
    }];
    
    [self.freshCheckImgBtn sizeToFit];
    
    // 图形验证码 图片
    [self.view addSubview:self.checkImgView];
    [self.checkImgView mas_makeConstraints:^(MASConstraintMaker* make) {
        make.right.equalTo(self.bottomView.mas_right).mas_offset(-(30 + self.freshCheckImgBtn.bounds.size.width) * kScaleWidth);
        make.width.mas_equalTo(72 * kScaleWidth);
        make.height.mas_equalTo(30 * kScaleHeight);
        make.centerY.equalTo(self.checkImgText);
    }];
    // 刷新按钮
    UIButton *refreshBtn = [[UIButton alloc] init];
    [refreshBtn addTarget:self action:@selector(freshCheckImgForgetPassword) forControlEvents:UIControlEventTouchUpInside];
    [self.checkImgView addSubview:refreshBtn];
    [refreshBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.checkImgView);
    }];
    
    // 图形验证码 ”换一张“
    [self.view addSubview:self.freshCheckImgBtn];
    [self.freshCheckImgBtn mas_makeConstraints:^(MASConstraintMaker* make) {
        make.right.equalTo(self.bottomView.mas_right).mas_offset(-15 * kScaleWidth);
        make.centerY.equalTo(self.checkImgView);
    }];

    [self.view addSubview:self.checkText];
    [self.checkText mas_makeConstraints:^(MASConstraintMaker* make) {
        make.top.equalTo(self.line4View.mas_bottom).mas_offset(5);
        make.bottom.equalTo(self.line2View.mas_top).mas_offset(-5);
        make.left.equalTo(self.bottomView).mas_offset(20);
        make.width.mas_equalTo(self.line2View).mas_offset(-105);
    }];

    [self.view addSubview:self.newpasswordText];
    [self.newpasswordText mas_makeConstraints:^(MASConstraintMaker* make) {
        make.top.equalTo(self.line2View.mas_bottom).mas_offset(5);
        make.bottom.equalTo(self.bottomView.mas_bottom).mas_offset(-5);
        make.left.equalTo(self.bottomView).mas_offset(20);
        make.width.mas_equalTo(self.line2View).mas_offset(-10);
    }];

    [self.view addSubview:self.getMessButton];
    [self.getMessButton mas_makeConstraints:^(MASConstraintMaker* make) {
        make.top.equalTo(self.line4View.mas_bottom).mas_offset(5);
        make.bottom.equalTo(self.line2View.mas_top).mas_offset(-5);
        make.right.equalTo(self.view).mas_offset(-15);
    }];

    //语音验证码
    [self.view addSubview:self.getSoundMsgButton];
    [self.getSoundMsgButton mas_makeConstraints:^(MASConstraintMaker* make) {
        make.top.equalTo(self.bottomView.mas_bottom).mas_offset(10);
        make.right.equalTo(self.bottomView.mas_right).mas_offset(-15);
        make.width.mas_greaterThanOrEqualTo(50);
        make.height.mas_equalTo(15);
    }];
    [self.view addSubview:self.getSoundMsgLabel];
    [self.getSoundMsgLabel mas_makeConstraints:^(MASConstraintMaker* make) {
        make.centerY.equalTo(self.getSoundMsgButton.mas_centerY);
//        make.top.equalTo(self.bottomView.mas_bottom).mas_offset(10);
        make.right.equalTo(self.getSoundMsgButton.mas_left);
        make.width.mas_greaterThanOrEqualTo(50);
        make.height.equalTo(self.getSoundMsgButton.mas_height);
//        make.height.mas_equalTo(11);
    }];
    
    [self.view addSubview:self.passwordRuleLabel];
    [self.passwordRuleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.getSoundMsgLabel.mas_bottom).offset(10);
        make.left.mas_equalTo(15);
        make.right.mas_equalTo(-15);
    }];
}

#pragma mark - NSNotification
- (void)handleUserDidTakeScreenshot:(NSNotification *)notification {
    [SEGAlertView showTmepMessageWithMessage:KDetectScreenShotTipMessage withtime:2];
}
- (void)handleScreenCapturedDidChange:(NSNotification *)notification {
    NSLog(@"%s %@", __func__, notification);
    if (@available(iOS 11.0, *)) {
        if ([UIScreen mainScreen].isCaptured) {
            [SEGAlertView showTmepMessageWithMessage:KDetectScreenCapturedTipMessage withtime:2];
        }
    }
}

#pragma mark - Event
// 刷新图片验证码
- (void)freshCheckImgForgetPassword {
    @weakify(self);
    [self.viewModel.refreshImgSignal subscribeNext:^(UIImage *decodedImage) {
        @strongify(self);
        if (decodedImage) {
            [self.checkImgView setImage:decodedImage];
        } else {
            [self.checkImgView setImage:[UIImage imageWithContentsOfFile:SEGPicName(@"pic_default_72_72")]];
        }
        // 确定按钮高亮状态
        [self updateSubmitButtonStatus];
    } error:^(NSError * _Nullable error) {
        [SEGAlertView showTmepMessageWithMessage:error.localizedFailureReason];
        // 确定按钮高亮状态
        [self updateSubmitButtonStatus];
    }];
}
// 发送验证码
- (void)getmessage {
    @weakify(self);
    [self.viewModel.captchasSignal subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        [SEGAlertView showTmepMessageWithMessage:@"验证码已发送"];
        [self sentPhoneCodeTimeMethod];
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        [SEGAlertView showTmepMessageWithMessage:error.localizedFailureReason];
        if (error.code == 1) {
            // 刷新图形验证码
            [self freshCheckImgForgetPassword];
        }
    }];
}
// 获取语音验证码
- (void)getSoundMessage {
    @weakify(self);
    [self.viewModel.soundCodeSignal subscribeNext:^(NSString *message) {
        @strongify(self);
        [SEGAlertView showTmepMessageWithMessage:message];
        [self sentPhoneCodeTimeMethod];
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        [SEGAlertView showTmepMessageWithMessage:error.localizedFailureReason];
        // 语音验证码失败清空&刷新图形验证码
        if (error.code == 1) {
            [self freshCheckImgForgetPassword];
        }
    }];
}
// 导航栏上，“确定”按钮触发方法
- (void)onNavigationRightButtonClicked:(UIButton *)sender {
    [self.view endEditing:YES];
    @weakify(self);
    [self.viewModel.sureBtnSignal subscribeNext:^(NSString *message) {
        @strongify(self);
        [SEGAlertView showTmepMessageWithMessage:message withtime:1.5];
        [SEGLoginV2Manager segSaveUserTelToLocal:self.phoneText.text];
        [SEGLoginV2Manager segSaveUserPasswordToLocal:@""];
        [[NSNotificationCenter defaultCenter] postNotificationName:kForgerPasswordSuccessNotification object:nil];
        [self.navigationController popViewControllerAnimated:YES];
    } error:^(NSError * _Nullable error) {
        if (error.code == 0) {
            [SEGAlertView showTmepMessageWithMessage:error.localizedFailureReason];
        } else {
            [SEGAlertView showTmepMessageWithMessage:error.localizedFailureReason withtime:1.5];
        }
    }];
}
// 计时器发送验证码
- (void)sentPhoneCodeTimeMethod {
    // 倒计时时间 —— 60秒
    __block NSInteger timeOut = 59;
    @weakify(self);
    self.disposable = [[RACSignal interval:1 onScheduler:[RACScheduler mainThreadScheduler]] subscribeNext:^(NSDate * _Nullable x) {
        @strongify(self);
        if (timeOut < 0) {
            [self.disposable dispose];
            [self.getMessButton setTitle:kRefreshGetMessageCodeTitle forState:UIControlStateNormal];
            self.getMessButton.enabled = YES;
            self.getSoundMsgButton.enabled = YES;
        } else {
            [UIView beginAnimations:nil context:nil];
            [UIView setAnimationDuration:1.0];
            [self.getMessButton setTitle:[NSString stringWithFormat:@"%ldS", timeOut] forState:UIControlStateNormal];
            self.getMessButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
            [UIView commitAnimations];
            // 计时器件不允许点击
            self.getMessButton.enabled = NO;
            self.getSoundMsgButton.enabled = NO;
            timeOut --;
        }
    }];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

#pragma mark - SGETextFieldLimitDelegate
- (void)limitTextFileDidChange:(UITextField *)textField {
    [self updateSubmitButtonStatus];
}
- (void)updateSubmitButtonStatus {
    if (self.phoneText.text.length > 0 && self.newpasswordText.text.length > 0 && self.checkText.text.length > 0 && self.checkImgText.text.length > 0) {
        self.confirmButton.enabled = YES;
    }  else {
        self.confirmButton.enabled = NO;
    }
}

#pragma mark - UITextFieldDelegate 键盘隐藏
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}
- (BOOL)textFieldShouldClear:(UITextField *)textField {
    return YES;
}

#pragma mark - Getter
// 手机号码，验证码，新密码背的白色背景框
- (UIView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[UIView alloc] init];
        _bottomView.backgroundColor = kColor_W;
    }
    return _bottomView;
}
// 第一根灰色分割线
- (UIView *)line1View {
    if (!_line1View) {
        _line1View = [[UIView alloc] init];
        _line1View.backgroundColor = kColor_L2;
    }
    return _line1View;
}
- (UIView *)line2View {
    if (!_line2View) {
        _line2View = [[UIView alloc] init];
        _line2View.backgroundColor = kColor_L2;
    }
    return _line2View;
}
// 输入手机号码textfield
- (UITextField *)phoneText {
    if (!_phoneText) {
        _phoneText = [[UITextField alloc] init];
        [_phoneText setTextColor:kColor_1];
        [_phoneText setFont:[UIFont systemFontOfSize:13]];
        [_phoneText setAttributedPlaceholder:[[NSAttributedString alloc] initWithString:@"手机号码" attributes:@{NSForegroundColorAttributeName:kColor_C}]];
        _phoneText.clearsOnBeginEditing = NO;
        _phoneText.delegate = self;
        _phoneText.clearButtonMode = UITextFieldViewModeWhileEditing;
        _phoneText.keyboardType = UIKeyboardTypeNumberPad;
        _phoneText.tintColor = kColor_T;
        _phoneText.text = self.phoneNumber;
        [_phoneText configPhoneInputLimitWithDelegate:self];
    }
    return _phoneText;
}
// 输入验证码textfield
- (UITextField *)checkText {
    if (!_checkText) {
        _checkText = [[UITextField alloc] init];
        [_checkText setTextColor:kColor_1];
        [_checkText setTintColor:kColor_T];
        [_checkText setFont:[UIFont systemFontOfSize:13]];
        [_checkText setAttributedPlaceholder:[[NSAttributedString alloc] initWithString:@"手机验证码" attributes:@{NSForegroundColorAttributeName:kColor_C}]];
        _checkText.clearsOnBeginEditing = NO;
        _checkText.clearButtonMode = UITextFieldViewModeWhileEditing;
        _checkText.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
        _checkText.delegate = self;
        _checkText.keyboardType = UIKeyboardTypeNumberPad;
        [_checkText configSMSCodeInputLimitWithDelegate:self];
    }
    return _checkText;
}
// 输入密码textfield
- (SEGPasswordTextField *)newpasswordText {
    if (!_newpasswordText) {
        _newpasswordText = [[SEGPasswordTextField alloc] init];
        [_newpasswordText setTextColor:kColor_1];
        [_newpasswordText setTintColor:kColor_T];
        [_newpasswordText setFont:[UIFont systemFontOfSize:13]];
        [_newpasswordText setAttributedPlaceholder:[[NSAttributedString alloc] initWithString:@"新密码" attributes:@{NSForegroundColorAttributeName:kColor_C}]];
        _newpasswordText.secureTextEntry = YES;
        _newpasswordText.clearsOnBeginEditing = NO;
        _newpasswordText.delegate = self;
        _newpasswordText.keyboardType = UIKeyboardTypeDefault;
        _newpasswordText.limitDelegate = self;
        [_newpasswordText configPasswordInputLimitWithDelegate:self currentView:self.view];
    }
    return _newpasswordText;
}
// 获取验证码按钮
- (UIButton *)getMessButton {
    if (!_getMessButton) {
        //发送验证码 按钮
        _getMessButton = [[UIButton alloc] init];
        [_getMessButton setTitle:kGetMessageCodeTitle forState:UIControlStateNormal];
        _getMessButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        _getMessButton.titleLabel.font = [UIFont systemFontOfSize:13];
        [_getMessButton setTitleColor:kColor_T forState:UIControlStateNormal];
        [_getMessButton setTitleColor:kColor_3 forState:UIControlStateDisabled];
        //发送事件
        [_getMessButton addTarget:self action:@selector(getmessage) forControlEvents:UIControlEventTouchUpInside];
    }
    return _getMessButton;
}
- (UILabel *)getSoundMsgLabel {
    if (!_getSoundMsgLabel) {
        _getSoundMsgLabel = [[UILabel alloc] init];
        _getSoundMsgLabel.textColor = kColor_1;
        _getSoundMsgLabel.font = [UIFont systemFontOfSize:11];
        _getSoundMsgLabel.text = @"收不到验证码？试试";
    }
    return _getSoundMsgLabel;
}
- (UIButton *)getSoundMsgButton {
    if (!_getSoundMsgButton) {
        //发送语音验证码 按钮
        _getSoundMsgButton = [[UIButton alloc] init];
        [_getSoundMsgButton setTitle:@"语音验证码" forState:UIControlStateNormal];
        [_getSoundMsgButton setTitleColor:kColor_S3 forState:UIControlStateNormal];
        [_getSoundMsgButton setTitleColor:kColor_3 forState:UIControlStateDisabled];
        _getSoundMsgButton.titleLabel.font = [UIFont systemFontOfSize:11];
        //发送事件
        [_getSoundMsgButton addTarget:self action:@selector(getSoundMessage) forControlEvents:UIControlEventTouchUpInside];
    }
    return _getSoundMsgButton;
}
- (UIView *)line4View {
    if (!_line4View) {
        _line4View = [[UIView alloc] init];
        _line4View.backgroundColor = kColor_L2;
    }
    return _line4View;
}
- (UIButton *)freshCheckImgBtn {
    if (!_freshCheckImgBtn) {
        // 发送语音验证码 按钮
        _freshCheckImgBtn = [[UIButton alloc] init];
        [_freshCheckImgBtn setTitle:@"换一张" forState:UIControlStateNormal];
        [_freshCheckImgBtn.titleLabel setFont:[UIFont systemFontOfSize:13]];
        [_freshCheckImgBtn setTitleColor:kColor_T forState:UIControlStateNormal];
        _freshCheckImgBtn.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
        // 发送事件
        [_freshCheckImgBtn addTarget:self action:@selector(freshCheckImgForgetPassword) forControlEvents:UIControlEventTouchUpInside];
    }
    return _freshCheckImgBtn;
}
// 图片验证码
- (UITextField *)checkImgText {
    if (!_checkImgText) {
        _checkImgText = [[UITextField alloc] init];
        [_checkImgText setTextColor:kColor_1];
        [_checkImgText setFont:[UIFont systemFontOfSize:13]];
        [_checkImgText setAttributedPlaceholder:[[NSAttributedString alloc] initWithString:@"图片验证码" attributes:@{NSForegroundColorAttributeName:kColor_C}]];
        _checkImgText.clearsOnBeginEditing = NO;
        _checkImgText.delegate = self;
        _checkImgText.clearButtonMode = UITextFieldViewModeNever;
        [_checkImgText setTintColor:kColor_T];
        [_checkImgText setKeyboardType:UIKeyboardTypeWebSearch];
        [_checkImgText configImgCodeInputLimitWithDelegate:self];
    }
    return _checkImgText;
}
- (UIImageView *)checkImgView {
    if (!_checkImgView) {
        _checkImgView = [[UIImageView alloc] initWithImage:[UIImage imageWithContentsOfFile:SEGPicName(@"pic_default_72_72")]];
        [_checkImgView setUserInteractionEnabled:YES];
    }
    return _checkImgView;
}
- (UILabel *)passwordRuleLabel {
    if (!_passwordRuleLabel) {
        _passwordRuleLabel = [[UILabel alloc] init];
        _passwordRuleLabel.textColor = kColor_C;
        _passwordRuleLabel.textAlignment = NSTextAlignmentRight;
        _passwordRuleLabel.font = kFont_13;
        _passwordRuleLabel.numberOfLines = 0;
    }
    return _passwordRuleLabel;
}
- (SEGForgetPasswordViewModel *)viewModel {
    if (!_viewModel) _viewModel = [[SEGForgetPasswordViewModel alloc] initWithPhoneNumber:self.phoneNumber];
    return _viewModel;
}

@end
